package com.cyzy.service.impl;

import com.cyzy.caster.DanmakuBroadcaster;
import com.cyzy.dto.DanmakuRequest;

import com.cyzy.service.DanmakuService;

import com.cyzy.service.MessageService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
public class DanmakuServiceImpl implements DanmakuService {

    @Resource
    private OkHttpClient okHttpClient;

    @Autowired
    private MessageService messageService;



    @Value("${baidu.qianfan.api.url:https://qianfan.baidubce.com/v2/chat/completions}")
    private String apiUrl;

    @Value("${baidu.qianfan.access-token}")
    private String apiKey;

    @Value("${baidu.qianfan.appid}")
    private String appId;

    @Value("${baidu.qianfan.model:ernie-speed-8k}")
    private String model;

    // 用于存储已处理的消息ID，避免重复处理
    private static final ConcurrentHashMap<String, Boolean> processedMessages = new ConcurrentHashMap<>();

    // 增强版本地过滤规则
    private static final Pattern SELF_INTRO_PATTERN = Pattern.compile(
            "^(我是|我叫|本人是|大家好，我是|大家好，我叫|俺是|咱是).*",
            Pattern.CASE_INSENSITIVE
    );

    private static final Pattern GREETING_PATTERN = Pattern.compile(
            "^(你好|您好|早上好|下午好|晚上好|晚安|再见|拜拜|谢谢|感谢|多谢).*",
            Pattern.CASE_INSENSITIVE
    );

    private static final Pattern STATEMENT_PATTERN = Pattern.compile(
            "^[^?]*$",
            Pattern.CASE_INSENSITIVE
    );

    private static final Pattern OBVIOUS_QUESTION_PATTERN = Pattern.compile(
            "^(什么是|为什么|怎么|如何|哪里|哪个|多少|吗|呢|？).*",
            Pattern.CASE_INSENSITIVE
    );

    @Override
    public String processDanmaku(DanmakuRequest request) throws IOException {
        String messageId = request.getContent() + "_" + request.getUserName();
        long currentTime = System.currentTimeMillis();
        String messageKey = messageId + "_" + (currentTime / 1000);

        if (processedMessages.putIfAbsent(messageKey, Boolean.TRUE) != null) {
            System.out.println("消息已处理，跳过: " + messageKey);
            return "";
        }
        try {
            String content = request.getContent();
            String userName = request.getUserName();
            String classId = request.getClassId(); // 获取班级ID
            Integer toUserid = request.getToUserid();
            System.out.println("收到用户[" +toUserid+"-"+ userName + "]的弹幕内容: " + content + "（班级: " + classId + "）");

            // 构造弹幕对象用于广播
            JSONObject danmakuObj = new JSONObject();
            danmakuObj.put("type", "danmaku");
            danmakuObj.put("content", content);
            danmakuObj.put("user", userName);
            danmakuObj.put("classId", classId); // 添加班级ID到广播消息
            danmakuObj.put("timestamp", System.currentTimeMillis());

            // 修正1：调整参数顺序，先班级ID，后消息内容
            DanmakuBroadcaster.broadcast(classId, danmakuObj.toString());

            // 本地过滤判断
            if (is明显非问题(content)) {
                System.out.println("本地过滤判定为非问题: " + content);
                return "";
            }

            if (is明显问题(content)) {
                System.out.println("本地判定为明显问题，直接生成回答");
                String answer = generateAnswer(content,userName,toUserid);
                broadcastAIReply(answer, userName, classId);
                return answer;
            }

            // AI判断是否为问题
            boolean isQuestion = isQuestion(content);
            System.out.println("AI判断是否为问题: " + isQuestion);

            if (!isQuestion) {
                return "";
            }

            String answer = generateAnswer(content,userName,toUserid);
            broadcastAIReply(answer, userName, classId);
            return answer;
        } finally {
            new Thread(() -> {
                try {
                    Thread.sleep(5000);
                    processedMessages.remove(messageId + "_" + (currentTime / 1000));
                } catch (InterruptedException e) {
                    // Ignore
                }
            }).start();
        }
    }

    //广播ai回答
    private void broadcastAIReply(String answer, String userName, String classId) {
        JSONObject aiReplyObj = new JSONObject();
        aiReplyObj.put("type", "ai_reply");
        aiReplyObj.put("content", answer);
        aiReplyObj.put("user", "AI助手");
        aiReplyObj.put("originalUser", userName);
        aiReplyObj.put("classId", classId); // 添加班级ID到AI回复
        aiReplyObj.put("timestamp", System.currentTimeMillis());

        // 修正2：调整参数顺序，先班级ID，后消息内容
        DanmakuBroadcaster.broadcast(classId, aiReplyObj.toString());
    }

    //本地判断
    private boolean is明显非问题(String content) {
        if (content == null || content.trim().isEmpty()) {
            return true;
        }

        if (SELF_INTRO_PATTERN.matcher(content).matches() ||
                GREETING_PATTERN.matcher(content).matches()) {
            return true;
        }

        if (STATEMENT_PATTERN.matcher(content).matches() && content.length() < 6) {
            return true;
        }

        if (content.matches(".*([\\s\\S])\\1{3,}.*")) {
            return true;
        }

        return false;
    }

   //利用正则判断是否为明显问题
    private boolean is明显问题(String content) {
        if (OBVIOUS_QUESTION_PATTERN.matcher(content).matches() ||
                content.contains("?") ||
                content.contains("？")) {
            return true;
        }

        if (content.matches(".*[^a-zA-Z0-9]?[a-zA-Z0-9]+=[^?]*\\?.*")) {
            return false;
        }

        return false;
    }

    //减少token的使用，判断问题只回答是/否
    private boolean isQuestion(String content) throws IOException {
        String prompt = "请严格判断以下内容是否为需要回答的问题，只返回一个字：是 或 否。内容：" + content;

        JSONObject json = new JSONObject();
        json.put("model", model);
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);
        json.put("messages", new JSONObject[]{message});
        json.put("max_completion_tokens", 2);  // 增加token数量
        json.put("temperature", 0.1);  // 降低随机性

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                json.toString()
        );

        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("appid", appId)
                .build();

        try (Response response = okHttpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "无错误内容";
                System.out.println("判断问题类型错误响应: " + errorBody);
                throw new IOException("判断问题类型请求失败: " + response.code());
            }

            String responseBody = response.body().string();
            System.out.println("AI判断原始响应: " + responseBody);  // 添加详细日志

            JSONObject responseJson = new JSONObject(responseBody);
            String result = responseJson.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content")
                    .trim();

            System.out.println("AI判断原始结果: '" + result + "'");

            // 增强判断逻辑
            boolean isQuestion = result.contains("是") && !result.contains("否");

            System.out.println("AI判断结果: '" + result + "', 最终判定: " + (isQuestion ? "是问题" : "非问题"));
            return isQuestion;
        }
    }

    //生成问题答案
    private String generateAnswer(String content, String userName,Integer toUserid) throws IOException {
        JSONObject json = new JSONObject();
        json.put("model", model);

        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "简要回答：" + content);
        json.put("messages", new JSONObject[]{message});

        json.put("max_completion_tokens", 50);
        json.put("temperature", 0.7);

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                json.toString()
        );

        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("appid", appId)
                .build();

        try (Response response = okHttpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("生成回答请求失败: " + response.code());
            }

            String answer = new JSONObject(response.body().string())
                    .getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
            System.out.println("userid"+toUserid);
            messageService.sendMessage("AI助手", toUserid, userName,answer);
            return "@" + userName + ":" + answer;
        }
    }
}
